package com.athl.demoreactor;

import com.athl.demoreactor.handler.UserHandler;
import com.athl.demoreactor.service.impl.UserServiceImpl;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;


/**
 * @author hl
 * @Data 2020/9/16
 */
public class Server {


    public static void main(String[] args) throws Exception {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("enter to exit");
        System.in.read();
    }

    /**
     * 1、创建Router路由
     */
    public RouterFunction<ServerResponse> routerFunction() {

        UserServiceImpl userService = new UserServiceImpl();
        UserHandler handler = new UserHandler(userService);

        /**
         * 2、设置方法对应的路由
         */
        return RouterFunctions.route(
                GET("/user/{id}").and(accept(APPLICATION_JSON)), handler::getUserById)
                .andRoute(GET("/users").and(accept(APPLICATION_JSON)), handler::getAllUser)
                .andRoute(POST("/save/user"), handler::saveUser);
    }

    /**
     * 3、创建服务器完成适配
     */
    public void createReactorServer() {
        RouterFunction<ServerResponse> router = routerFunction();
        HttpHandler httpHandler = toHttpHandler(router);
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
        /**
         * 4、创建服务器
         */
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(adapter).bindNow();
    }
}
